package top.snowlands.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import top.snowlands.constant.MessageConstant;
import top.snowlands.constant.RedisConstant;
import top.snowlands.entity.PageResult;
import top.snowlands.entity.QueryPageBean;
import top.snowlands.entity.Result;
import top.snowlands.pojo.Setmeal;
import top.snowlands.service.SetmealService;
import top.snowlands.utils.QiniuUtils;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    /**
     * 使用jedisPool操作redis服务
     */
    @Autowired
    private JedisPool jedisPool;


    @Reference
    private SetmealService setmealService;

     /**
     * 文件上传
     */
    @RequestMapping("/upload")
    public Result upload(@RequestParam("imgFile") MultipartFile imgFile){
        System.out.println(imgFile);
        String originalFilename = imgFile.getOriginalFilename();//获得原始文件名
        int index = originalFilename.lastIndexOf(".");
        String extension = originalFilename.substring(index);//包含点的扩展名
        String fileName= UUID.randomUUID().toString()+extension;
        try {
            QiniuUtils.upload2Qiniu(imgFile.getBytes(),fileName);
            Jedis resource = jedisPool.getResource();
            resource.sadd(RedisConstant.SETMEAL_PIC_RESOURCES,fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }
        return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS,fileName);
    }

    /**
     * 新增套餐
     */
    @RequestMapping("/add")
    public Result add(@RequestBody Setmeal setmeal, Integer[] checkgroupIds){
        try{
            System.out.println("SetmealController");
            setmealService.add(setmeal,checkgroupIds);

        }catch (Exception e){
            e.printStackTrace();
            return new Result(true,MessageConstant.ADD_SETMEAL_FAIL);
        }
        return new Result(true,MessageConstant.ADD_SETMEAL_SUCCESS);
    }

    /**
     * 分页查询
     */
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        return setmealService.pageQuery(queryPageBean);
    }
}
